package com.voicechat.firstmet.view.recyclerview.mo;

import android.content.Context;
import android.graphics.Canvas;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;

/**
 * Created by Lym on 2018/1/6.
 */

public class MoCardCallback extends ItemTouchHelper.SimpleCallback {

    private static final String TAG = "MoCardCallback";
    private static final int MAX_ROTATION = 10;
    private static final int ANIMATION_REMOVE_TORIGHT = 10010;
    private final int mHorizontalDeviation;
    OnSwipeListener mSwipeListener;
    boolean isSwipeAnim = false;
    private boolean slip = true;//是否可滑动
    private RecyclerView mRv;
    public static float SCALE_GAP = 0.10f;
    //判断 此次滑动方向是否是竖直的 ，水平方向上的误差(阈值，默认我给了50dp)
    private View currentView;
    private Context context;

    public MoCardCallback(RecyclerView mRv, Context context) {
        //第一个参数决定可以拖动排序的方向, 这里由于不需要拖动排序,所以传0
        //第二个参数决定可以支持滑动的方向,这里设置了上下左右都可以滑动.
        super(0, ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP);
        mHorizontalDeviation = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, mRv.getContext().getResources().getDisplayMetrics());
        this.mRv = mRv;
        this.context=context;
    }

    public void setSwipeListener(OnSwipeListener swipeListener) {
        mSwipeListener = swipeListener;
    }

    @Override
    public int interpolateOutOfBoundsScroll(RecyclerView recyclerView, int viewSize, int viewSizeOutOfBounds, int totalSize, long msSinceStartScroll) {
        return super.interpolateOutOfBoundsScroll(recyclerView, viewSize, viewSizeOutOfBounds, totalSize, msSinceStartScroll);
    }
    /* * 获得逃脱(swipe)速度
     *
     * @param defaultValue
     * @return
     */
    @Override
    public float getSwipeEscapeVelocity(float defaultValue) {
        View topView = mRv.getChildAt(mRv.getChildCount() - 1);
        if (isUpOrDown(topView)) {
            return Float.MAX_VALUE;
        }
        return super.getSwipeEscapeVelocity(defaultValue);
    }
   /**
     * 获得swipe的速度阈值
     * @param defaultValue
     * @return
     */
    @Override
    public float getSwipeVelocityThreshold(float defaultValue) {
        View topView = mRv.getChildAt(mRv.getChildCount() - 1);
        if (isUpOrDown(topView)) {
            return Float.MAX_VALUE;
        }
        return super.getSwipeVelocityThreshold(defaultValue);
    }
    @Override
    public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
       // Log.i(TAG, "getSwipeThreshold: ");
        if (isUpOrDown(viewHolder.itemView)) { //如果是向上或者向下滑动
            return Float.MAX_VALUE; //就返回阈值为很大
        }
        return 0.5f;
    }
    /**
     * 判断是否是向上滑或者向下滑
     */
    private boolean isUpOrDown(View topView) {
        float x = topView.getX();
        float y = topView.getY();
        int left = topView.getLeft();
        int top = topView.getTop();
        if (Math.pow(x - left, 2) > Math.pow(y - top, 2)) {
            //水平方向大于垂直方向
//            Log.i(TAG, "isUpOrDown: 不是");
            return false;
        } else {
            return true;
//            Log.i(TAG, "isUpOrDown: 是");
        }
    }

   /* @Override
    public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
*//*        Log.d("TAG", "getSwipeThreshold() called with: viewHolder.itemView.getX() = [" + viewHolder.itemView.getX() + "]");
        Log.d("TAG", "getSwipeThreshold() called with:  viewHolder.itemView.getWidth() / 2  = [" + viewHolder.itemView.getWidth() / 2 + "]");
        Log.d("TAG", "getSwipeThreshold() called with:  mRv.getX() = [" + mRv.getX() + "]");
        Log.d("TAG", "getSwipeThreshold() called with:  mRv.getWidth() / 2 = [" + mRv.getWidth() / 2 + "]");*//*

        if (isTopViewCenterInHorizontal(viewHolder.itemView)) {
            return Float.MAX_VALUE;
        }
        return super.getSwipeThreshold(viewHolder);
    }

    @Override
    public float getSwipeEscapeVelocity(float defaultValue) {
        View topView = mRv.getChildAt(mRv.getChildCount() - 1);
        if (isTopViewCenterInHorizontal(topView)) {
            return Float.MAX_VALUE;
        }
        return super.getSwipeEscapeVelocity(defaultValue);
    }

    @Override
    public float getSwipeVelocityThreshold(float defaultValue) {

        View topView = mRv.getChildAt(mRv.getChildCount() - 1);
        if (isTopViewCenterInHorizontal(topView)) {
            return Float.MAX_VALUE;
        }
        return super.getSwipeVelocityThreshold(defaultValue);
    }*/

    /**
     * 返回TopView此时在水平方向上是否是居中的
     *
     * @return
     *//*
    public boolean isTopViewCenterInHorizontal(View topView) {
        Log.d("TAG", "getSwipeThreshold() called with: viewHolder.itemView.getX() = [" + topView.getX() + "]");
        Log.d("TAG", "getSwipeThreshold() called with:  viewHolder.itemView.getWidth() / 2  = [" + topView.getWidth() / 2 + "]");
        Log.d("TAG", "getSwipeThreshold() called with:  mRv.getX() = [" + mRv.getX() + "]");
        Log.d("TAG", "getSwipeThreshold() called with:  mRv.getWidth() / 2 = [" + mRv.getWidth() / 2 + "]");
        return Math.abs(mRv.getWidth() / 2 - topView.getX() - (topView.getWidth() / 2)) < mHorizontalDeviation;
    }*/


    //水平方向是否可以被回收掉的阈值
    public float getThreshold(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        return recyclerView.getWidth() * getSwipeThreshold(viewHolder) ;//0.5f
    }
    public void setIsSlip(boolean isSlip) {//设置是否可以滑动
        this.slip = isSlip;
    }
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        Log.d("Linfo", "onMove: ");
        //由于不支持滑动排序, 所以不需要处理此方法
        return false;
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
    }


    /**
     * 当某个Item被滑动到消失时回调，direction表示滑动的方向。
     *
     * @param viewHolder
     * @param direction
     */
    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        //当view需要滑动的时候,会回调此方法
        //但是这个方法只是告诉你View需要滑动, 并不是对View和Adapter进行额外的操作,
        //所以, 如果你需要实现滑动删除, 那么需要在此方法中remove item等.

        //我们这里需要对滑动过后的View,进行恢复操作.
        viewHolder.itemView.setRotation(0);//恢复最后一次的旋转状态
        if (mSwipeListener != null) {
            mSwipeListener.onSwipeTo(viewHolder, 0, 0);
        }
        notifyListener(viewHolder.getAdapterPosition(), direction);
    }

    private void notifyListener(int position, int direction) {
        if (mSwipeListener != null) {
            mSwipeListener.onSwiped(position, direction);
        }
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return slip;
    }
    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                            float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        //当你在滑动的过程中, 此方法一直会被回调, 就跟onTouch事件一样...
        //先根据滑动的dx dy 算出现在动画的比例系数fraction
        //先根据滑动的dxdy 算出现在动画的比例系数fraction
        double swipValue = Math.sqrt(dX * dX + dY * dY);
        double fraction = swipValue / getThreshold(recyclerView,viewHolder);
        //边界修正 最大为1
        if (fraction > 1) {
            fraction = 1;
        }
        int childCount = recyclerView.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = recyclerView.getChildAt(i);
            //第几层,举例子，count =7， 最后一个TopView（6）是第0层，
            int level = childCount - i - 1;
            if (level > 0) {
               // child.setTranslationY((float) (SCALE_GAP * (level - 1) - fraction * SCALE_GAP));
               // child.setScaleX((float) (1 - SCALE_GAP * level + fraction * SCALE_GAP));
               // child.setTranslationY((float) (SCALE_GAP * (level - 1) - fraction * SCALE_GAP));
                //child.setScaleX((float) (1 - MoCardLayoutManager.SCALE_GAP * level + fraction * MoCardLayoutManager.SCALE_GAP));
              //  if (level < 4 - 1) {
                    //child.setScaleY((float) (1 - SCALE_GAP * level + fraction * SCALE_GAP));
//                    child.setTranslationY((float) (TRANS_Y_GAP * level - fraction * TRANS_Y_GAP));
//                } else {
                    //child.setTranslationY((float) (SCALE_GAP * (level - 1) - fraction * SCALE_GAP));
              //  }
                child.setRotation(0);
            } else {
               float xFraction = dX / getThreshold(recyclerView,viewHolder);
                //边界修正 最大为1
                 if (xFraction > 1) {
                    xFraction = 1;
                } else if (xFraction < -1) {
                    xFraction = -1;
                }
                //rotate
                child.setRotation(xFraction * MAX_ROTATION);
                if (mSwipeListener != null) {
                    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
                    final int adapterPosition = params.getViewAdapterPosition();
                    mSwipeListener.onSwipeTo(recyclerView.findViewHolderForAdapterPosition(adapterPosition), dX, dY);
                }
            }
        }
        //可以在此判断左右滑：
//        float v = mRv.getWidth() / 2 - viewHolder.itemView.getX() - (viewHolder.itemView.getWidth() / 2);
//        if (v > 0) {
//            isLeftSwipe = true;
//        } else if (v < 0) {
//            isLeftSwipe = false;
//        }

       /* float swipeValue = (float) Math.sqrt(dX * dX + dY * dY);
        final float threshold = getThreshold(recyclerView, viewHolder);
        float fraction = swipeValue / threshold;
        //边界修正 最大为1
        if (fraction > 1) {
            fraction = 1;
        } else if (fraction < -1) {
            fraction = -1;
        }
        //对每个ChildView进行缩放 位移
        int childCount = recyclerView.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = recyclerView.getChildAt(i);
            //第几层,举例子，count =7， 最后一个TopView（6）是第0层，
            int level = childCount - i - 1;
            if (level > 0) {
                child.setScaleX(1 - MoCardLayoutManager.SCALE_GAP * level + fraction * MoCardLayoutManager.SCALE_GAP);

                if (level < MoCardLayoutManager.MAX_SHOW_COUNT - 1) {
                    child.setScaleY(1 - MoCardLayoutManager.SCALE_GAP * level + fraction * MoCardLayoutManager.SCALE_GAP);
                    child.setTranslationY(MoCardLayoutManager.TRANS_Y_GAP * level - fraction * MoCardLayoutManager.TRANS_Y_GAP);
                } else {
                    //child.setTranslationY((float) (MoCardLayoutManager.mTranslationYGap * (level - 1) - fraction * mTranslationYGap));
                }
            } else {
                //最上层 最外层旋转(第一个)
                //rotate
                if (dX < -50) {
                   // child.setRotation(-fraction * MAX_ROTATION);
                    child.setRotation(-fraction * 10);
                } else if (dX > 50) {
                   // child.setRotation(fraction * MAX_ROTATION);
                    child.setRotation(fraction * 10);
                } else {
                    child.setRotation(0);
                }

                if (mSwipeListener != null) {
                    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
                    final int adapterPosition = params.getViewAdapterPosition();
                    mSwipeListener.onSwipeTo(recyclerView.findViewHolderForAdapterPosition(adapterPosition), dX, dY);
                    //mSwipeListener.onSwipeIng(recyclerView.findViewHolderForAdapterPosition(adapterPosition),adapterPosition);
                }
            }
        }*/
    }
    //一个flag 判断左右滑
    private boolean isLeftSwipe;
    //扩展实现:点击按钮实现左滑效果
    public void toLeft(RecyclerView recyclerView) {
        if (check(recyclerView)) {
            animTo(recyclerView, false);
            /*if (recyclerView == null) {
                return;
            }
            final int position = recyclerView.getAdapter().getItemCount() - 1;
            final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
            if (viewHolder == null) {
                return;
            }
            final View view = viewHolder.itemView;
            currentView = view;
            isSwipeAnim = false;
            recyclerView.removeView(view);
            view.setRotation(1 * MAX_ROTATION);
            notifyListener(position, ItemTouchHelper.LEFT );*/
        }
    }
    //扩展实现:点击按钮实现右滑效果
    public void toRight(RecyclerView recyclerView) {
        if (check(recyclerView)) {
            animTo(recyclerView, true);
           /* if (recyclerView == null) {
                return;
            }
            final int position = recyclerView.getAdapter().getItemCount() - 1;
            final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
            if (viewHolder == null) {
                return;
            }
            final View view = viewHolder.itemView;
            currentView = view;
            isSwipeAnim = false;
            recyclerView.removeView(view);
            view.setRotation(1 * MAX_ROTATION);
            notifyListener(position, ItemTouchHelper.RIGHT );*/
        }
    }
    private void animTo(final RecyclerView recyclerView, final boolean right) {
        if (recyclerView == null) {
            return;
        }
        final int position = recyclerView.getAdapter().getItemCount() - 1;
        final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
        if (viewHolder == null) {
            return;
        }
        final View view = viewHolder.itemView;
        currentView = view;
        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, right ? 1f : -1f,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0.5f);
        translateAnimation.setFillAfter(true);
        translateAnimation.setDuration(300);
        translateAnimation.setInterpolator(new DecelerateInterpolator());
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }
            @Override
            public void onAnimationEnd(Animation animation) {
                isSwipeAnim = false;
                view.setRotation(0);
                //recyclerView.removeView(view);
                notifyListener(position, right ? ItemTouchHelper.RIGHT : ItemTouchHelper.LEFT);
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        view.startAnimation(translateAnimation);
    }

    private boolean check(RecyclerView recyclerView) {
        if (isSwipeAnim) {
            Log.d("Linfo", "isSwipeAnim");//点太快,问题
            return false;
        }
        if (recyclerView == null || recyclerView.getAdapter() == null) {
            return false;
        }
        if (recyclerView.getAdapter().getItemCount() == 0) {
            return false;
        }
        isSwipeAnim = true;
        return true;
    }

    public void setisSwipeAnim(boolean isEnd) {
        isSwipeAnim = isEnd;
    }

    public interface OnSwipeListener {

        /**
         * @param direction {@link ItemTouchHelper#LEFT} / {@link ItemTouchHelper#RIGHT}
         *                  {@link ItemTouchHelper#UP} or {@link ItemTouchHelper#DOWN}).
         */
        void onSwiped(int adapterPosition, int direction);

        /**
         * 最上层View滑动时回调.
         *
         * @param viewHolder 最上层的ViewHolder
         * @param offXset    距离原始位置的X轴的偏移量
         * @param offYset    距离原始位置的Y轴的偏移量
         */
        void onSwipeTo(RecyclerView.ViewHolder viewHolder, float offXset, float offYset);
        //void onSwipeIng(RecyclerView.ViewHolder viewHolder,int adapterPosition);

    }

   /* public static class SimpleSwipeCallback implements OnSwipeListener {

        *//**
         * {@inheritDoc}
         *//*
        @Override
        public void onSwiped(int adapterPosition, int direction) {

        }

        *//**
         * {@inheritDoc}
         *//*
        @Override
        public void onSwipeTo(RecyclerView.ViewHolder viewHolder, float offXset, float offYset) {

        }
    }*/
}
